package example1;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.junit.Test;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;

public class VideoTest {
    static String videofileDir = "C:/Users/yangyang/Desktop/抖音douyin";
    static String framefile = "C:/Users/yangyang/Desktop/抖音douyin封面";

    @Test
    public void t3() throws IOException {
        Collection<File> filesAndDirs = FileUtils.listFilesAndDirs(FileUtils.getFile(videofileDir), TrueFileFilter.INSTANCE, DirectoryFileFilter.DIRECTORY);
        List<ImgEntity> list = new LinkedList<>();

        for (File file : filesAndDirs) {
            if (file.isDirectory()) continue;
            if (file.getName().endsWith(".mp4") == false) continue;
            String fileName = file.getName();
            String substring = fileName.substring(0, fileName.lastIndexOf("."));

            ImgEntity imgEntity = new ImgEntity();

            long l = file.lastModified();
            //lastModifiedTime
            Date date = new Date(l);
            String format = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");

            imgEntity.setLastModified(l);
            imgEntity.setLastModifiedFormat(format);
            imgEntity.setName(substring);
            list.add(imgEntity);
        }
        //排序
        Collections.sort(list, new Comparator<ImgEntity>() {
            @Override
            public int compare(ImgEntity o1, ImgEntity o2) {
                int i = o1.getLastModified().compareTo(o2.getLastModified());
                return i;
            }
        });
        //
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setSort(i + 1);
        }
        //
        Collections.reverse(list);
        //
        String data = JSONObject.toJSONString(list);
        //JSONArray jsonArray = JSONObject.parseArray(data);
        String formatJson = formatJson(data);
        FileUtils.writeStringToFile(FileUtils.getFile("C:/Users/yangyang/Desktop/抖音douyin封面List.json"), formatJson, "UTF-8");
    }

    @Test
    public void t2() throws IOException {
        File file = new File("C:/Users/yangyang/Desktop/抖音douyin/0ada6cfeac5435149576d38b74930b06.mp4");
        long l = file.lastModified();
        //lastModifiedTime
        Date date = new Date(l);
        String format = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
        System.out.println(format);

        List<String> query = new LinkedList<>();
        String data = JSONObject.toJSONString(query);
        //JSONArray jsonArray = JSONObject.parseArray(data);
        String formatJson = formatJson(data);
        FileUtils.writeStringToFile(FileUtils.getFile("C:/Users/yangyang/Desktop/抖音douyin封面List.json"), formatJson, "UTF-8");
    }

    /**
     * 格式化JSON字符串
     *
     * @param data JSON字符串
     * @return 格式化后JSON字符串
     */
    public String formatJson(String data) {
        Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(data);
        String pretty = gson.toJson(je);
        return pretty;
    }

    @Test
    public void t1() {
        Collection<File> filesAndDirs = FileUtils.listFilesAndDirs(FileUtils.getFile(videofileDir), TrueFileFilter.INSTANCE, DirectoryFileFilter.DIRECTORY);
        LinkedList<String> list = new LinkedList<>();
        for (File file : filesAndDirs) {
            if (file.isDirectory()) continue;
            String fileName = file.getName();
            String substring = fileName.substring(0, fileName.lastIndexOf("."));
            String imgName = substring + ".jpeg";


            if (file.getName().endsWith(".mp4")) {
                try {
                    genImg(file, FileUtils.getFile(framefile, imgName));
                } catch (Exception e) {
                    System.out.println(file);
                    list.add(file.getName());
                    e.printStackTrace();
                    //System.exit(0);
                }
            }
        }
        System.out.println("------------------- 华丽的分割线 ---------------------");
        System.out.println(StringUtils.join(list, "\n"));
    }


    public void genImg(File videofile, File framefile) throws Exception {
        File targetFile = framefile;
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videofile);
        ff.start();
        int lenght = ff.getLengthInFrames();
        int i = 0;
        Frame f = null;
        while (i < lenght) {
            // 过滤前5帧，避免出现全黑的图片，依自己情况而定
            f = ff.grabFrame();
            if ((i > 48) && (f.image != null)) {
                break;
            }
            i++;
        }
        //        IplImage img = f.image;
        int owidth = f.imageWidth;
        int oheight = f.imageHeight;
        // 对截取的帧进行等比例缩放
//        int width = 300;
//        int height = (int) (((double) width / owidth) * oheight);

        int width = owidth;
        int height = oheight;

        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage fecthedImage = converter.getBufferedImage(f);
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        bi.getGraphics().drawImage(fecthedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        ImageIO.write(bi, "jpg", targetFile);
        ff.stop();
    }
}
